package org.jeecg.api.controller.position;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.api.annotation.ApiNeedLogin;
import org.jeecg.api.dto.req.UserPageReq;
import org.jeecg.api.dto.req.position.WorkSignDto;
import org.jeecg.api.dto.resp.position.MMUserWorkCollectionResultDto;
import org.jeecg.api.dto.resp.position.MMUserWorkSignResultDto;
import org.jeecg.api.dto.resp.position.MmCompanyPositionPageVO;
import org.jeecg.api.utils.MiniappSpringContextUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.util.SignDO;
import org.jeecg.common.system.vo.DictModel;
import org.jeecg.modules.recruit.appuser.entity.MmUserPositionCollection;
import org.jeecg.modules.recruit.appuser.service.IMmUserPositionCollectionService;
import org.jeecg.modules.recruit.company.entity.MmCompanyMain;
import org.jeecg.modules.recruit.company.service.IMmCompanyMainService;
import org.jeecg.modules.recruit.position.entity.MmCompanyLabel;
import org.jeecg.modules.recruit.position.entity.MmCompanyPicture;
import org.jeecg.modules.recruit.position.entity.MmCompanyPosition;
import org.jeecg.modules.recruit.position.entity.MmCompanyPositionItem;
import org.jeecg.modules.recruit.position.service.IMmCompanyLabelService;
import org.jeecg.modules.recruit.position.service.IMmCompanyPictureService;
import org.jeecg.modules.recruit.position.service.IMmCompanyPositionItemService;
import org.jeecg.modules.recruit.position.service.IMmCompanyPositionService;
import org.jeecg.modules.recruit.sign.entity.MmUserSign;
import org.jeecg.modules.recruit.sign.service.IMmUserSignService;
import org.jeecg.modules.system.service.ISysDictService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author zhongchao
 * @tile WxMiniappPositionController
 * @date 2020/8/24
 * @since v1.0.0
 */
@RestController
@RequestMapping("/app/position")
@Api(tags = "APP-职位信息")
public class WxMiniappPositionController {

    @Autowired
    private IMmCompanyPositionService mmCompanyPositionService;
    @Autowired
    private IMmCompanyPositionItemService mmCompanyPositionItemService;
    @Autowired
    private IMmCompanyPictureService mmCompanyPictureService;
    @Autowired
    private IMmCompanyLabelService mmCompanyLabelService;
    @Autowired
    private IMmCompanyMainService mmCompanyMainService;
    @Autowired
    private IMmUserSignService mmUserSignService;
    @Autowired
    private ISysDictService iSysDictService;
    @Autowired
    private IMmUserPositionCollectionService mmUserPositionCollectionService;

    @GetMapping("sign")
    @ApiOperation("工作报名")
    @ApiNeedLogin
    public Result<Boolean> workSign(WorkSignDto workSignDto) {
        SignDO signDO = MiniappSpringContextUtils.getSignDO();
        workSignDto.setUserId(signDO.getUserId());
        mmUserSignService.workSign(workSignDto);
        return Result.OK();
    }

    @GetMapping("positionInfo")
    @ApiOperation("职位信息")
    public Result<?> positionInfo(HttpServletRequest request,
                                                              @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                              @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                              MmCompanyPosition mmCompanyPosition) {
        // Step.1 组装查询条件查询数据
        mmCompanyPosition.setPsStatus(1);
        QueryWrapper<MmCompanyPosition> queryWrapper = QueryGenerator.initQueryWrapper(mmCompanyPosition, request.getParameterMap());
        Page<MmCompanyPosition> page = new Page<MmCompanyPosition>(pageNo, pageSize);
        IPage<MmCompanyPosition> pageLists = mmCompanyPositionService.page(page, queryWrapper);

        //Step.2 查询
        List<MmCompanyPosition> queryList = pageLists.getRecords();

        // Step.3 组装pageList
        List<MmCompanyPositionPageVO> pageList = new ArrayList<MmCompanyPositionPageVO>();
        for (MmCompanyPosition main : queryList) {
            MmCompanyPositionPageVO vo = new MmCompanyPositionPageVO();
            BeanUtils.copyProperties(main, vo);
            List<MmCompanyPositionItem> mmCompanyPositionItemList = mmCompanyPositionItemService.selectByMainId(main.getId());
            vo.setMmCompanyPositionItemList(mmCompanyPositionItemList);
            List<MmCompanyPicture> mmCompanyPictureList = mmCompanyPictureService.selectByMainId(main.getId());
            vo.setMmCompanyPictureList(mmCompanyPictureList);
            List<MmCompanyLabel> mmCompanyLabelList = mmCompanyLabelService.selectByMainId(main.getId());
            vo.setMmCompanyLabelList(mmCompanyLabelList);
            MmCompanyMain mmCompanyMain = mmCompanyMainService.getById(main.getCompanyId());
            vo.setMmCompanyMain(mmCompanyMain);
            pageList.add(vo);
        }

        Page<MmCompanyPositionPageVO> positionPage = new Page<>(pageLists.getCurrent(), pageSize, pageLists.getTotal());
        positionPage.setRecords(pageList);
        return Result.OK(positionPage);
    }

    @GetMapping("positionDetail")
    @ApiOperation("职位详情")
    public Result<MmCompanyPositionPageVO> positionDetail(HttpServletRequest request,
                                                          @RequestParam(name = "id", required = true) String id
    ) {

        SignDO signDO = MiniappSpringContextUtils.getSignDO();
        String userId = null;
        if (signDO != null) {
            userId = signDO.getUserId();
        }

        MmCompanyPosition mmCompanyPosition = mmCompanyPositionService.getById(id);
        if (mmCompanyPosition == null) {
            return Result.error("未获取到职位信息");
        }
        MmCompanyPositionPageVO vo = new MmCompanyPositionPageVO();
        BeanUtils.copyProperties(mmCompanyPosition, vo);
        //组装查询职位详情项
        List<DictModel> dictModelList = iSysDictService.queryDictItemsByCode("position_item_type");
        List<MmCompanyPositionItem> mmCompanyPositionItemList = mmCompanyPositionItemService.selectByMainId(mmCompanyPosition.getId());
        for (MmCompanyPositionItem mmCompanyPositionItem : mmCompanyPositionItemList) {
            List<DictModel> positioneDict = dictModelList.stream().filter(e -> (mmCompanyPositionItem.getItemType() + "").equals(e.getValue())).collect(Collectors.toList());
            if (positioneDict.size() > 0) {
                mmCompanyPositionItem.setItemName(positioneDict.get(0).getText());
            }
        }
        vo.setMmCompanyPositionItemList(mmCompanyPositionItemList);
        List<MmCompanyPicture> mmCompanyPictureList = mmCompanyPictureService.selectByMainId(mmCompanyPosition.getId());
        vo.setMmCompanyPictureList(mmCompanyPictureList);
        List<MmCompanyLabel> mmCompanyLabelList = mmCompanyLabelService.selectByMainId(mmCompanyPosition.getId());
        vo.setMmCompanyLabelList(mmCompanyLabelList);
        MmCompanyMain mmCompanyMain = mmCompanyMainService.getById(mmCompanyPosition.getCompanyId());
        vo.setMmCompanyMain(mmCompanyMain);
        vo.setSignNum(mmUserSignService.lambdaQuery().eq(MmUserSign::getPositionId, mmCompanyPosition.getId()).count());
        //是否收藏
        QueryWrapper<MmUserPositionCollection> queryWrapper = new QueryWrapper<MmUserPositionCollection>();
        queryWrapper.eq("position_id", id);
        queryWrapper.eq("user_id", userId);
        MmUserPositionCollection mmUserPositionCollection = mmUserPositionCollectionService.getOne(queryWrapper);
        if (mmUserPositionCollection != null && userId != null) {
            vo.setCollection(true);
        } else {
            vo.setCollection(false);
        }
        //是否报名
        QueryWrapper<MmUserSign> signWrapper = new QueryWrapper<MmUserSign>();
        signWrapper.eq("position_id", id);
        signWrapper.eq("user_id", userId);
        MmUserSign mmUserSign = mmUserSignService.getOne(signWrapper);
        if (mmUserSign != null && userId != null) {
            vo.setSign(true);
        } else {
            vo.setSign(false);
        }
        return Result.OK(vo);
    }

    @ApiNeedLogin
    @GetMapping("isPositionSign")
    @ApiOperation("是否已经报名")
    public Result<Boolean> isPositionSign(
            @RequestParam(name = "positionid", defaultValue = "") String positionid) {
        SignDO signDO = MiniappSpringContextUtils.getSignDO();
        if (signDO == null) {
            return Result.OK(false);
        }
        List<MmUserSign> list = mmUserSignService.lambdaQuery()
                .eq(MmUserSign::getUserId, signDO.getUserId())
                .eq(MmUserSign::getPositionId, positionid).list();
        return Result.OK(list.size() > 0);
    }

    @ApiNeedLogin
    @ApiOperation(value = "职位收藏记录-添加", notes = "职位收藏记录-添加")
    @PostMapping(value = "/collectionAdd")
    public Result<?> add(@RequestParam(name = "id", required = true) String id) {
        String userId = MiniappSpringContextUtils.getSignDO().getUserId();

        MmUserPositionCollection mmUserPositionCollection = new MmUserPositionCollection();
        mmUserPositionCollection.setPositionId(id);
        mmUserPositionCollection.setUserId(userId);
        mmUserPositionCollectionService.save(mmUserPositionCollection);
        return Result.ok("添加成功！");
    }

    @ApiNeedLogin
    @ApiOperation(value = "职位收藏删除", notes = "职位收藏删除")
    @PostMapping(value = "/collectionDel")
    public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
        String userId = MiniappSpringContextUtils.getSignDO().getUserId();
        QueryWrapper<MmUserPositionCollection> collectionQueryWrapper = new QueryWrapper<MmUserPositionCollection>();
        collectionQueryWrapper.eq("position_id", id);
        collectionQueryWrapper.eq("user_id", userId);
        mmUserPositionCollectionService.remove(collectionQueryWrapper);
        return Result.ok("删除成功!");
    }

//    @ApiNeedLogin
//    @ApiOperation(value="获取关注列表", notes="获取关注列表")
//    @GetMapping(value = "/collectionList")
//    public Result<?> collectionList(HttpServletRequest request,
//                                    @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
//                                    @RequestParam(name="pageSize", defaultValue="10") Integer pageSize) {
//        String userId = MiniappSpringContextUtils.getSignDO().getUserId();
//        //查询关注列表
//        MmUserPositionCollection mmUserPositionCollection = new MmUserPositionCollection();
//        mmUserPositionCollection.setUserId(userId);
//        QueryWrapper<MmUserPositionCollection> queryWrapper = QueryGenerator.initQueryWrapper(mmUserPositionCollection, request.getParameterMap());
//        Page<MmUserPositionCollection> page = new Page<MmUserPositionCollection>(pageNo, pageSize);
//        IPage<MmUserPositionCollection> pageLists = mmUserPositionCollectionService.page(page, queryWrapper);
//        //set职位信息
//        List<MmCompanyPosition> pageList = new ArrayList<MmCompanyPosition>();
//        for(MmUserPositionCollection mmUserPositionCollection1:pageLists.getRecords()){
//            QueryWrapper<MmCompanyPosition> positionQueryWrapper = new QueryWrapper<MmCompanyPosition>();
//            positionQueryWrapper.eq("id", mmUserPositionCollection1.getPositionId());
//            pageList.add(mmCompanyPositionService.getById(mmUserPositionCollection1.getPositionId()));
//        }
//        Page<MmCompanyPosition> positionPage = new Page<>(pageNo,pageSize);
//        positionPage.setRecords(pageList);
//        return Result.OK(positionPage);
//    }

    @ApiNeedLogin
    @GetMapping("signlist")
    @ApiOperation(value = "获取报名列表", notes = "获取报名列表")
    public Result<Page<MMUserWorkSignResultDto>> getUserSignList(UserPageReq req) {
        SignDO signDO = MiniappSpringContextUtils.getSignDO();
        req.setUserId(signDO.getUserId());
        return Result.OK(mmUserSignService.getUserSignList(req));
    }

    @ApiNeedLogin
    @GetMapping("collectionlist")
    @ApiOperation(value = "获取用户关注列表对象", notes = "获取用户关注列表对象")
    public Result<Page<MMUserWorkCollectionResultDto>> getUserCollectionList(UserPageReq req) {
        SignDO signDO = MiniappSpringContextUtils.getSignDO();
        req.setUserId(signDO.getUserId());
        return Result.OK(mmUserPositionCollectionService.getUserCollectionList(req));
    }


}
